import axios, { InternalAxiosRequestConfig, AxiosRequestConfig, AxiosResponse } from 'axios'
import { ElMessage } from 'element-plus'
import { useUserStore } from '@/store/modules/user'
import EmojiText from '../emojo'
import JSONBig from 'json-bigint'
import { router } from '@/router'
const jsonBigInstance = JSONBig({ storeAsString: true })
const axiosInstance = axios.create({
  timeout: 60 * 1000, // 请求超时时间(毫秒)
  baseURL: import.meta.env.VITE_API_URL, // API地址
  withCredentials: true, // 异步请求携带cookie
  transformRequest: [
    (data) => {
      if (data instanceof FormData) {
        return data
      }
      return JSON.stringify(data)
    }
  ], // 请求数据转换为 JSON 字符串
  validateStatus: (status) => status >= 200 && status < 300, // 只接受 2xx 的状态码
  headers: {
    get: { 'Content-Type': 'application/x-www-form-urlencoded;charset=utf-8' },
    post: { 'Content-Type': 'application/json;charset=utf-8' }
  },
  transformResponse: [
    (data) => {
      try {
        return jsonBigInstance.parse(data)
      } catch (err) {
        console.log(err)
        return JSON.parse(data)
      }
    }
  ]
})

// 请求拦截器
axiosInstance.interceptors.request.use(
  (request: InternalAxiosRequestConfig) => {
    const { accessToken } = useUserStore()

    // 如果 token 存在，则设置请求头
    if (accessToken) {
      request.headers.set({
        'Content-Type': 'application/json',
        Authorization: accessToken
      })
    }
    return request // 返回修改后的配置
  },
  (error) => {
    ElMessage.error(`服务器异常！ ${EmojiText[500]}`) // 显示错误消息
    return Promise.reject(error) // 返回拒绝的 Promise
  }
)

// 响应拦截器
axiosInstance.interceptors.response.use(
  (response: AxiosResponse) => {
    if (response.data.code === 0) {
      return response
    } else {
      if (response.data.code == 1401) {
        const userStore = useUserStore()
        userStore.logOut()
        router.push('/login')
        // window.location.href = '/login'
      }
      if (response.data.msg) {
        ElMessage.error(response.data.msg)
      }
      return Promise.reject(response.data)
    }
  },
  (error) => {
    if (axios.isCancel(error)) {
      console.log('repeated request: ' + error.message)
    } else {
      const errorMessage = error.response?.data.message
      ElMessage.error(
        errorMessage
          ? `${errorMessage} ${EmojiText[500]}`
          : `请求超时或服务器异常！${EmojiText[500]}`
      )
    }
    return Promise.reject(error)
  }
)

// 请求
async function request<T = any>(config: AxiosRequestConfig): Promise<T> {
  try {
    const res = await axiosInstance.request<T>({ ...config })
    return res.data
  } catch (e) {
    if (axios.isAxiosError(e)) {
      console.log(e)
      // 可以在这里处理 Axios 错误  
    }
    return Promise.reject(e)
  }
}

const requestPost = <T = any>(url: string, config: AxiosRequestConfig): Promise<T> => {
  return request<T>({ url, ...config })
}

export default requestPost
